package com.example.common.domain.pojo.Converter;


import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Converter(autoApply = true)  // autoApply=true 表示对所有匹配类型自动应用此转换器
@Slf4j
public class MapToListJsonConverter implements AttributeConverter<Map<String, List<String>>, String> {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String convertToDatabaseColumn(Map<String, List<String>> attribute) {
        if (attribute == null) {
            return null;
        }
        try {
            return objectMapper.writeValueAsString(attribute);
        } catch (IOException e) {
            log.error("Map转JSON失败，属性值：{}", attribute, e);
            throw new IllegalArgumentException("Error converting Map to JSON", e);
        }
    }

    @Override
    public Map<String, List<String>> convertToEntityAttribute(String dbData) {
        if (dbData == null) {
            return null;
        }
        try {
            // 使用 TypeReference 明确指定反序列化类型
            return objectMapper.readValue(dbData,
                    new TypeReference<Map<String, List<String>>>() {
                    });
        } catch (IOException e) {
            log.error("JSON转Map失败，数据库值：{}", dbData, e);
            throw new IllegalArgumentException("Error converting JSON to Map", e);
        }
    }
}
